<?php
namespace app\api\controller;

use app\common\model\CustomerModel;
use app\common\model\FinancialRecordsModel;
use app\common\model\JobModel;

/**
 * Class Index
 * @package app\index\controller
 */
class Debash extends Base
{


    public function __construct(\think\App $app)
    {
        parent::__construct($app);
    }


    public function index(){

        // 首页统计数据计算接口
        $this->checkUserLogin();

        

        $result = [];

        $month = input('month', date('Y-m'));
        // 计算环比
        $current_month_start = date($month . '-01 00:00:00');
        $current_month_end = date($month . '-d 23:59:59');
        $current_map = [];
        $current_map[] = ['status', '=', 1];
        $current_map[] = ['create_time', 'between', [strtotime($current_month_start), strtotime($current_month_end)]];

        $last_month_start = date('Y-m-01 00:00:00', strtotime('-1 month', strtotime($current_month_start)));
        $last_month_end = date('Y-m-d 23:59:59', strtotime('-1 month', strtotime($current_month_start)));

        $last_map = [];
        $last_map[] = ['status', '=', 1];
        $last_map[] = ['create_time', 'between', [strtotime($last_month_start), strtotime($last_month_end)]];


        // 计算新增任务
        $current_task_map = [];
        $current_task_map[] = ['is_deleted', '=', 0];
        $current_task_map[] = ['create_time', 'between', [strtotime($current_month_start), strtotime($current_month_end)]];
        $last_task_map = [];
        $last_task_map[] = ['is_deleted', '=', 0];
        $last_task_map[] = ['create_time', 'between', [strtotime($last_month_start), strtotime($last_month_end)]];
        
        // 财务统计
        $current_finacial_map = [];
        $current_finacial_map[] = ['status', '=', 1];
        $current_finacial_map[] = ['created_at', 'between', [$current_month_start, $current_month_end]];
        $current_finacial_map[] = ['transaction_type', '=', 'expense'];


        $last_finacial_map = [];
        $last_finacial_map[] = ['status', '=', 1];
        $last_finacial_map[] = ['created_at', 'between', [$current_month_start, $current_month_end]];
        $last_finacial_map[] = ['transaction_type', '=', 'income'];

        
        // 统计最近10天的新增客户数量,按日期升序排序，若当天无数据，则补0
        $customer_map = [];
        $customer_map[] = ['status', '=', 1];
        $customer_map[] = ['create_time', 'between', [strtotime('-10 day'), time()]];

        if(!$this->checkIsAdmin()){
            $current_map['boyi_uid'] = $this->user['id'];
            $last_map['boyi_uid'] = $this->user['id'];
            $current_task_map['boyi_uid'] = $this->user['id'];
            $last_task_map['boyi_uid'] = $this->user['id'];
            $current_finacial_map['boyi_uid'] = $this->user['id'];
            $last_finacial_map['boyi_uid'] = $this->user['id'];
            $customer_map['boyi_uid'] = $this->user['id'];
        }

        $current_map['is_deleted'] = 0;
        $last_map['is_deleted'] = 0;
        $customer_map['is_deleted'] = 0;


        // 客户数量以及总金额
        $current_count = CustomerModel::where($current_map)->field('count(*) customer_num, sum(amount) amount_sum, sum(received_amount) received_amount_sum, sum(reback_amount) reback_amount_sum')->find();
        $last_count = CustomerModel::where($last_map)->field('count(*) customer_num, sum(amount) amount_sum, sum(received_amount) received_amount_sum, sum(reback_amount) reback_amount_sum')->find();

        $customer_num = $current_count['customer_num'] ?? 0;
        $last_customer_num = $last_count['customer_num'] ?? 0;
        $amount_sum = $current_count['amount_sum'] ?? 0;
        $last_amount_sum = $last_count['amount_sum'] ?? 0;

        $received_amount_sum = $current_count['received_amount_sum'] ?? 0;
        $last_received_amount_sum = $last_count['received_amount_sum'] ?? 0;
        $reback_amount_sum = $current_count['reback_amount_sum'] ?? 0;
        $last_reback_amount_sum = $last_count['reback_amount_sum'] ?? 0;
        $reback_amount_sum_ratio = $last_count['reback_amount_sum'] > 0 ? round(($current_count['reback_amount_sum'] - $last_count['reback_amount_sum']) / $last_count['reback_amount_sum'] * 100, 2) : 100;
        $customer_num_ratio = $last_count['customer_num'] > 0 ? round(($current_count['customer_num'] - $last_count['customer_num']) / $last_count['customer_num'] * 100, 2) : 100;
        $amount_sum_ratio = $last_count['amount_sum'] > 0 ? round(($current_count['amount_sum'] - $last_count['amount_sum']) / $last_count['amount_sum'] * 100, 2) : 0;
        $received_amount_sum_ratio = $last_count['received_amount_sum'] > 0 ? round(($current_count['received_amount_sum'] - $last_count['received_amount_sum']) / $last_count['received_amount_sum'] * 100, 2) : 100;





        $current_task_count = JobModel::where($current_task_map)->field('count(*) task_num')->find();
        $last_task_count = JobModel::where($last_task_map)->field('count(*) task_num')->find();
        $task_num = $current_task_count['task_num'] ?? 0;
        $last_task_num = $last_task_count['task_num'] ?? 0;
        $task_num_ratio = $last_task_num > 0 ? round(($task_num - $last_task_num) / $last_task_num * 100, 2) : 100;


        // 计算支出的金额。
        $finacial = FinancialRecordsModel::where($current_finacial_map)->field('sum(amount) amount_sum')->find();
        $current_expense_amount_sum = $finacial['amount_sum'] ?? 0;
        $current_finacial_map[] = ['created_at', 'between', [$last_month_start, $last_month_end]];
        $last_finacial = FinancialRecordsModel::where($current_finacial_map)->field('sum(amount) amount_sum')->find();
        $last_expense_amount_sum = $last_finacial['amount_sum'] ?? 0;
        $expense_amount_sum_ratio = $last_expense_amount_sum > 0 ? round(($current_expense_amount_sum - $last_expense_amount_sum) / $last_expense_amount_sum * 100, 2) : 100;

        // 计算收入的金额
        $finacial = FinancialRecordsModel::where($last_finacial_map)->field('sum(amount) amount_sum')->find();
        $current_income_amount_sum = $finacial['amount_sum'] ?? 0;
        $last_finacial_map[] = ['created_at', 'between', [$last_month_start, $last_month_end]];
        $last_finacial = FinancialRecordsModel::where($last_finacial_map)->field('sum(amount) amount_sum')->find();
        $last_income_amount_sum = $last_finacial['amount_sum'] ?? 0;
        $income_amount_sum_ratio = $last_income_amount_sum > 0 ? round(($current_income_amount_sum - $last_income_amount_sum) / $last_income_amount_sum * 100, 2) : 100;



        $customer_count = CustomerModel::where($customer_map)->field('count(*) customer_num, sum(amount) sum_amount, FROM_UNIXTIME(create_time, "%Y-%m-%d") create_date')->group('create_date')->select();
        $trend = [];
        $customer_arr = $customer_count->toArray();
        $customer_count = array_column($customer_arr, 'customer_num', 'create_date');
        $amount_count = array_column($customer_arr, 'sum_amount', 'create_date');
        

        $customer_data = [];
        $amount_data = [];

        $xaxis = [];
        for ($i = 10; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime('-' . $i . ' day'));
            $customer_data[] = $customer_count[$date] ?? 0;
            $amount_data[] = $amount_count[$date] ?? 0;
            $xaxis[] = date('m-d', strtotime($date));
        }


        $customer_trend = [
            'name' => '新增客户',
            'type' => 'line',
            'data' => $customer_data,
            'symbol' => 'circle',
            'smooth' => true,
            'yAxisIndex' => 0,
            'showSymbol' => false,
            'areaStyle' => [
              'opacity' => 0.8,
            ],
        ];
        $amount_trend = [
            'name' => '新增营业额',
            'type' => 'line',
            'data' => $amount_data,
            'symbol' => 'circle',
            'smooth' => true,
            'yAxisIndex' => 0,
            'showSymbol' => false,
            'areaStyle' => [
              'opacity' => 0.8,
            ],
        ];
        $trend[] = $customer_trend;
        $trend[] = $amount_trend;
            


        $top_card = [
            [
                'title' => '本月营业额',
                'prefix' => '￥',
                'startVal' => 0,
                'background' => 'blue',
                'endVal' => floatval($amount_sum),
                'separator' => ',',
                'percentage' => $amount_sum_ratio . '%',
                'icon' => "money-cny-circle-line",
                'min_icon' => $amount_sum_ratio > 0 ? 'arrow-up-line' : 'arrow-down-line',
                'duration' => 3000
            ],
            [
                'title' => '本月收款',
                'prefix' => '￥',
                'startVal' => 0,
                'background' => 'white',
                'endVal' => floatval($current_income_amount_sum),
                'separator' => ',',
                'icon' => 'coins-line',
                'min_icon' => $income_amount_sum_ratio > 0 ? 'arrow-up-line' : 'arrow-down-line',
                'percentage' => $income_amount_sum_ratio . '%',
                'duration' => 3000
            ],
            [
                'title' => '本月支出',
                'prefix' => '￥',
                'startVal' => 0,
                'background' => 'black',
                'endVal' => floatval($current_expense_amount_sum),
                'separator' => ',',
                'icon' => 'creative-commons-nc-line',
                'min_icon' => $expense_amount_sum_ratio > 0 ? 'arrow-up-line' : 'arrow-down-line',
                'percentage' => $expense_amount_sum_ratio . '%',
                'duration' => 3000
            ],
            [
                'title' => '本月新增客户',
                'prefix' => '￥',
                'startVal' => 0,
                'background' => 'red',
                'endVal' => floatval($customer_num),
                'separator' => ',',
                'icon' => 'user-search-line',
                'min_icon' => $customer_num_ratio > 0 ? 'arrow-up-line' : 'arrow-down-line',
                'percentage' => $customer_num_ratio . '%',
                'duration' => 3000
            ],
        ];
        return $this->returnSuccess([
            'top_card' => $top_card,
            'trend' => $trend,
            'xaxis' => $xaxis,
        ]);
    }


}